<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-09 17:07:43
 * Desc:
 */

namespace app\base\behavior;

use think\Response;
use think\Request;
use think\Log;

class CorsRun
{
    public function run(&$dispatch)
    {

        $request = Request::instance();
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            $headers = [
                "Access-Control-Allow-Origin" => $_SERVER['HTTP_ORIGIN'],
                "Access-Control-Allow-Credentials" => 'true',
                "Access-Control-Allow-Methods" => 'GET, POST, PUT, DELETE, OPTIONS',
                "Access-Control-Allow-Headers" => "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Content-Language, Last-Event-ID, Cache-Control, Connection, Cookie, Host, Pragma, Referer, User-Agent, UA, AUTHORIZATION, authorization"
            ];
            Log::info('跨域处理 url : ' . $request->baseUrl() . ' method : ' . $request->method());

            if ($dispatch instanceof Response) {
                $dispatch->header($headers);
            } elseif ($request->isOptions()) {
                $dispatch['type'] = 'response';
                $response = new Response('', 200, $headers);
                $dispatch['response'] = $response;
            }

        }
    }
}